package com.acme.serialization.impl;

import com.acme.serialization.ObjectSerializer;
import com.acme.serialization.SerializationException;

import java.io.*;

/**
 * @author Gregory Sobko
 */
public class JavaObjectSerializer<T> implements ObjectSerializer<T> {
    @Override
    public String getProtocolName() {
        return "java";
    }

    @Override
    public T deserialize(InputStream inputStream) throws SerializationException {
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
            return (T)objectInputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            throw new SerializationException(e);
        }
    }

    @Override
    public void serialize(T object, OutputStream outputStream) throws SerializationException {
        try {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(object);
        } catch (IOException e) {
            throw new SerializationException(e);
        }
    }
}
